package com.jvtd.rxjava;

import android.util.Log;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class JvtdTokenInterceptor implements Interceptor {
    private static final String TAG = "JvtdTokenInterceptor";
    private int tokenError;
    private OnTokenListener mOnTokenListener;

    //获取token并保存本地
    public interface OnTokenListener{
        String getNewToken();//返回添加到头部的token信息
    }

    public JvtdTokenInterceptor(int error, OnTokenListener onTokenListener) {
        this.tokenError = error;
        this.mOnTokenListener = onTokenListener;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        Log.d(TAG, "response.code=" + response.code());

        //根据和服务端的约定判断token过期
        if (isTokenExpired(response)) {
            Log.d(TAG, "自动刷新Token,然后重新请求数据");
            //同步请求方式，获取最新的Token
            String newToken = mOnTokenListener.getNewToken();
            //使用新的Token，创建新的请求
            Request newRequest = chain.request()
                    .newBuilder()
                    .header("Authorization", newToken)
                    .build();
            //重新请求
            return chain.proceed(newRequest);
        }
        return response;
    }

    /**
     * 根据Response，判断Token是否失效
     */
    private boolean isTokenExpired(Response response) {
        return response.code() == tokenError;
    }
}
